import { writeFile, mkdir, access } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { constants } from 'node:os';
import path from 'path';
import config from '../../config.js';
function file(ctx) {
  return new Promise((resolve, reject) => {
    try {
      const body = [];
      ctx.req.addListener('data', (buffer) => {
        body.push(buffer);
      });
      ctx.req.on('end', () => {
        let [, boundary] = ctx.req.headers['content-type'].split('boundary=');
        let chunks = Buffer.concat(body);
        boundary = '--' + boundary;
        chunks = chunks.subarray(
          chunks.indexOf(boundary) + boundary.length,
          chunks.length - boundary.length - 4,
        );
        let blockIndex = chunks.indexOf('\r\n\r\n');
        const info = chunks.subarray(0, blockIndex);
        let [, line1, line2] = info.toString().split('\r\n');
        let [, name, filename] = line1.split(';');
        let [, type] = line2.split(':');
        name = name.split('=')?.[1]?.replace(/"/g, '');
        filename = filename.split('=')?.[1]?.replace(/"/g, '');
        chunks = chunks.subarray(blockIndex + 4);
        console.log({
          total: chunks.length / 1024,
          name,
          filename,
          type,
        });
        resolve({
          data: chunks,
          total: chunks.length,
          name,
          filename,
          type,
        });
      });
    } catch (err) {
      reject(err);
    }
  });
}
const uploadToData = () => {
  return async (ctx, next) => {
    try {
      if (
        ctx.req.method === 'POST' &&
        ctx.req.headers?.['content-type'] &&
        ctx.req.headers?.['content-type']?.indexOf?.('multipart/form-data') !== -1
      ) {
        const { total, name, filename, data } = await file(ctx);
        if (!total) {
          ctx.file = null;
        } else {
          const uploadPath = config.uploadPath;
          const isExists = existsSync(uploadPath);
          if (!isExists) {
            await mkdir(uploadPath, { recursive: true });
          }
          await writeFile(path.join(uploadPath, filename), data);
          ctx.file = {
            fileData: data,
            url: filename,
          };
        }
      }
    } catch (e) {
      console.log(e);
      ctx.file = null;
    }
    await next();
  };
};

export default uploadToData;
